extends Window
class_name PhantomBeastWindow

## 幻兽系统悬浮窗口
## 负责显示幻兽列表、详细信息和队伍编成功能

# 常量定义
const SLOT_SIZE = Vector2(64, 64)  # 格子大小
const GRID_COLS = 5  # 每行格子数
const MAX_BEAST_SLOTS = 200  # 最大幻兽格子数
const DRAG_THRESHOLD_TIME = 0.2  # 拖拽阈值时间

# UI节点引用
@onready var beast_grid: GridContainer = $HBoxContainer/BeastListPanel/VBoxContainer/ScrollContainer/BeastGrid

# PlayerHUD引用
var player_hud: Control = null
@onready var sort_button: Button = $HBoxContainer/BeastListPanel/VBoxContainer/HeaderContainer/SortButton
@onready var select_all_button: Button = $HBoxContainer/BeastInfoPanel/VBoxContainer/MultiSelectContainer/SelectAllButton
@onready var batch_sell_button: Button = $HBoxContainer/BeastInfoPanel/VBoxContainer/MultiSelectContainer/BatchSellButton
@onready var gold_label: Label = $HBoxContainer/BeastListPanel/VBoxContainer/HeaderContainer/GoldLabel
@onready var beast_info_panel: Panel = $HBoxContainer/BeastInfoPanel
@onready var beast_name_label: Label = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/BeastNameLabel
@onready var beast_level_label: Label = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/BeastLevelLabel
@onready var beast_exp_label: Label = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/BeastExpLabel
@onready var nickname_line_edit: LineEdit = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/NicknameContainer/NicknameLineEdit
@onready var nickname_button: Button = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/NicknameContainer/NicknameButton
@onready var beast_stats_label: RichTextLabel = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/BeastStatsLabel
@onready var beast_description_label: Label = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/BeastDescriptionLabel
@onready var formation_button: Button = $HBoxContainer/BeastInfoPanel/VBoxContainer/ButtonContainer/FormationButton
@onready var sell_button: Button = $HBoxContainer/BeastInfoPanel/VBoxContainer/ButtonContainer/SellButton
@onready var revive_button: Button = $HBoxContainer/BeastInfoPanel/VBoxContainer/ButtonContainer/ReviveButton
@onready var close_button: Button = $HBoxContainer/BeastInfoPanel/VBoxContainer/ButtonContainer/CloseButton

# 合成系统UI
@onready var synthesis_container: VBoxContainer = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/SynthesisContainer
@onready var synthesis_title_label: Label = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/SynthesisContainer/SynthesisTitleLabel
@onready var material_slots_container: HBoxContainer = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/SynthesisContainer/MaterialSlotsContainer
@onready var synthesis_info_label: Label = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/SynthesisContainer/SynthesisInfoLabel
@onready var synthesis_button: Button = $HBoxContainer/BeastInfoPanel/VBoxContainer/ScrollContainer/InfoContainer/SynthesisContainer/SynthesisButton

# 队伍相关UI
@onready var formation_container: VBoxContainer = $HBoxContainer/FormationPanel/VBoxContainer/FormationContainer
@onready var formation_slots: Array[Control] = []

# 幻兽格子系统
var beast_slots: Array[Control] = []  # 幻兽格子UI数组
var beast_slot_data: Array[Dictionary] = []  # 幻兽格子数据数组

# 拖拽系统
var is_dragging: bool = false
var drag_preview: Control = null
var drag_source_slot: Control = null
var drag_source_index: int = -1
var drag_beast_data: Dictionary = {}
var mouse_press_time: float = 0.0
var mouse_press_slot: Control = null
var is_mouse_pressed: bool = false
var drag_start_slot: Control = null
var dragged_beast_id: String = ""
var dragged_from_slot_index: int = -1

# 双击检测
var last_click_time: float = 0.0
var last_click_slot: Control = null
var double_click_threshold: float = 0.5  # 双击时间阈值

# 高亮显示
var highlighted_slot: Control = null

# 当前选中的幻兽
var selected_beast_id: String = ""
var selected_slot_index: int = -1
var current_beasts: Array[Dictionary] = []
var active_formation: Array[String] = []

# 多选功能
var selected_beasts_for_sale: Array[Dictionary] = []  # 选中用于卖出的幻兽列表

# 合成系统
var material_slots: Array[Control] = []  # 副宠槽位UI
var material_beast_ids: Array[String] = ["", ""]  # 副宠ID数组
var is_synthesis_mode: bool = false  # 是否处于合成模式

# 信号
# signal ui_closed  # 暂时注释掉未使用的信号

func _ready():
	# 初始化UI
	setup_ui()
	create_beast_grid()
	setup_synthesis_ui()
	refresh_beast_grid()
	refresh_formation_display()
	update_gold_display()
	
	# 连接信号
	formation_button.pressed.connect(_on_formation_button_pressed)
	sell_button.pressed.connect(_on_sell_button_pressed)
	revive_button.pressed.connect(_on_revive_button_pressed)
	close_button.pressed.connect(_on_close_button_pressed)
	close_requested.connect(_on_close_button_pressed)
	synthesis_button.pressed.connect(_on_synthesis_button_pressed)
	nickname_button.pressed.connect(_on_nickname_button_pressed)
	sort_button.pressed.connect(_on_sort_button_pressed)
	select_all_button.pressed.connect(_on_select_all_button_pressed)
	batch_sell_button.pressed.connect(_on_batch_sell_button_pressed)
	
	# 连接幻兽管理器信号
	if PhantomBeastManager != null:
		PhantomBeastManager.phantom_beast_obtained.connect(_on_beast_obtained)
		PhantomBeastManager.phantom_beast_level_up.connect(_on_beast_level_up)
		PhantomBeastManager.formation_changed.connect(_on_formation_changed)
		PhantomBeastManager.phantom_beast_synthesized.connect(_on_beast_synthesized)
	
	# 连接玩家属性管理器信号
	if PlayerStatsManager != null:
		PlayerStatsManager.gold_changed.connect(_on_gold_changed)

func setup_ui():
	"""初始化UI设置"""
	# 设置窗口属性
	title = "幻兽系统"
	
	# 设置最小尺寸限制
	var min_width = 800
	var min_height = 600
	min_size = Vector2i(min_width, min_height)
	
	# 创建队伍编成槽位
	for i in range(4):
		var slot_container = _create_formation_slot(i)
		formation_slots.append(slot_container)
		formation_container.add_child(slot_container)
	
	# 初始化幻兽格子数据数组
	beast_slot_data.resize(MAX_BEAST_SLOTS)
	for i in range(MAX_BEAST_SLOTS):
		beast_slot_data[i] = {}

func _setup_window_size():
	"""动态设置窗口大小"""
	# 获取PlayerHUD大小
	var player_hud_size = player_hud.size if player_hud else get_viewport().get_visible_rect().size
	
	# 设置窗口大小为PlayerHUD大小减去像素
	size = Vector2i(int(player_hud_size.x), int(player_hud_size.y - 40))
	position = Vector2i(0, 35)

func toggle_visibility():
	"""切换窗口显示状态"""
	if visible:
		hide()
	else:
		# 显示窗口前动态设置窗口大小
		_setup_window_size()
		show()
		refresh_beast_grid()
		refresh_formation_display()
		
		# 打印窗口大小信息
		var player_hud_size = player_hud.size if player_hud else Vector2.ZERO
		var window_size = size
		var beast_list_panel_size = beast_grid.get_parent().get_parent().size if beast_grid and beast_grid.get_parent() and beast_grid.get_parent().get_parent() else Vector2.ZERO
		var beast_grid_size = beast_grid.size if beast_grid else Vector2.ZERO
		print("=== 幻兽窗口大小信息 ===")
		print("PlayerHUD大小: ", player_hud_size)
		print("幻兽窗口大小: ", window_size)
		print("幻兽列表面板大小: ", beast_list_panel_size)
		print("幻兽格子容器大小: ", beast_grid_size)
		print("========================")

func create_beast_grid():
	"""创建幻兽格子系统"""
	if beast_grid == null:
		return
	
	# 设置网格属性
	beast_grid.columns = GRID_COLS
	
	# 创建所有格子
	for i in range(MAX_BEAST_SLOTS):
		var slot_ui = _create_beast_slot(i)
		beast_slots.append(slot_ui)
		beast_grid.add_child(slot_ui)

func setup_synthesis_ui():
	"""初始化合成系统UI"""
	if synthesis_container == null:
		return
	
	# 创建副宠槽位
	for i in range(2):
		var material_slot = _create_material_slot(i)
		material_slots.append(material_slot)
		material_slots_container.add_child(material_slot)
		# 连接副宠槽位的输入事件
		material_slot.gui_input.connect(_on_material_slot_input.bind(i))
	
	# 初始化合成界面显示
	synthesis_container.visible = true  # 始终显示合成界面
	synthesis_title_label.text = "幻兽合成"
	synthesis_info_label.text = "选择主宠后，将同类型同星级的副宠拖拽到下方槽位进行合成"
	synthesis_button.text = "合成"
	synthesis_button.disabled = true

func _create_material_slot(index: int) -> Control:
	"""创建副宠槽位"""
	var slot_container = Control.new()
	slot_container.custom_minimum_size = SLOT_SIZE
	slot_container.size = SLOT_SIZE
	slot_container.name = "MaterialSlot" + str(index)
	
	# 创建带边框的背景面板
	var background = Panel.new()
	background.size = SLOT_SIZE
	background.anchors_preset = Control.PRESET_FULL_RECT
	
	# 创建样式资源并设置边框
	var style_box = StyleBoxFlat.new()
	style_box.bg_color = Color(0.2, 0.2, 0.3, 0.9)  # 深蓝色背景
	style_box.border_width_left = 2
	style_box.border_width_right = 2
	style_box.border_width_top = 2
	style_box.border_width_bottom = 2
	style_box.border_color = Color(0.6, 0.6, 0.8, 1.0)  # 淡蓝色边框
	style_box.corner_radius_top_left = 5
	style_box.corner_radius_top_right = 5
	style_box.corner_radius_bottom_left = 5
	style_box.corner_radius_bottom_right = 5
	background.add_theme_stylebox_override("panel", style_box)
	slot_container.add_child(background)
	
	# 创建幻兽图标
	var beast_icon = TextureRect.new()
	beast_icon.name = "BeastIcon"
	beast_icon.size = SLOT_SIZE
	beast_icon.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
	beast_icon.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	beast_icon.visible = false
	slot_container.add_child(beast_icon)
	
	# 创建等级标签
	var level_label = Label.new()
	level_label.name = "LevelLabel"
	level_label.size = Vector2(20, 20)
	level_label.position = Vector2(SLOT_SIZE.x - 20, SLOT_SIZE.y - 20)
	level_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	level_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	level_label.add_theme_font_size_override("font_size", 8)
	level_label.add_theme_color_override("font_color", Color.WHITE)
	level_label.visible = false
	slot_container.add_child(level_label)
	
	# 创建星级标签
	var star_label = Label.new()
	star_label.name = "StarLabel"
	star_label.size = Vector2(20, 20)
	star_label.position = Vector2(2, 2)
	star_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	star_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	star_label.add_theme_font_size_override("font_size", 8)
	star_label.add_theme_color_override("font_color", Color.YELLOW)
	star_label.visible = false
	slot_container.add_child(star_label)
	
	# 创建提示标签
	var hint_label = Label.new()
	hint_label.name = "HintLabel"
	hint_label.size = SLOT_SIZE
	hint_label.text = "副宠" + str(index + 1)
	hint_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	hint_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	hint_label.add_theme_font_size_override("font_size", 10)
	hint_label.add_theme_color_override("font_color", Color(0.7, 0.7, 0.7, 1.0))
	slot_container.add_child(hint_label)
	
	return slot_container

func _create_beast_slot(index: int) -> Control:
	"""创建单个幻兽格子"""
	var slot_container = Control.new()
	slot_container.custom_minimum_size = SLOT_SIZE
	slot_container.size = SLOT_SIZE
	
	# 创建带边框的背景面板
	var background = Panel.new()
	background.size = SLOT_SIZE
	background.anchors_preset = Control.PRESET_FULL_RECT
	
	# 创建样式资源并设置边框
	var style_box = StyleBoxFlat.new()
	style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)  # 深灰色背景
	style_box.border_width_left = 1
	style_box.border_width_right = 1
	style_box.border_width_top = 1
	style_box.border_width_bottom = 1
	style_box.border_color = Color(0.5, 0.5, 0.5, 1.0)  # 灰色边框
	style_box.corner_radius_top_left = 3
	style_box.corner_radius_top_right = 3
	style_box.corner_radius_bottom_left = 3
	style_box.corner_radius_bottom_right = 3
	background.add_theme_stylebox_override("panel", style_box)
	slot_container.add_child(background)
	
	# 创建幻兽图标
	var beast_icon = TextureRect.new()
	beast_icon.name = "BeastIcon"
	beast_icon.size = SLOT_SIZE
	beast_icon.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
	beast_icon.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	beast_icon.visible = false
	slot_container.add_child(beast_icon)
	
	# 创建等级标签
	var level_label = Label.new()
	level_label.name = "LevelLabel"
	level_label.size = Vector2(20, 20)
	level_label.position = Vector2(SLOT_SIZE.x - 20, SLOT_SIZE.y - 20)
	level_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	level_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	level_label.add_theme_font_size_override("font_size", 8)
	level_label.add_theme_color_override("font_color", Color.WHITE)
	level_label.visible = false
	slot_container.add_child(level_label)
	
	# 创建星级标签
	var star_label = Label.new()
	star_label.name = "StarLabel"
	star_label.size = Vector2(30, 15)
	star_label.position = Vector2(2, 2)
	star_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_LEFT
	star_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	star_label.add_theme_font_size_override("font_size", 8)
	star_label.add_theme_color_override("font_color", Color.YELLOW)
	star_label.visible = false
	slot_container.add_child(star_label)
	
	# 创建上阵标记
	var formation_mark = Label.new()
	formation_mark.name = "FormationMark"
	formation_mark.size = Vector2(20, 20)
	formation_mark.position = Vector2(SLOT_SIZE.x - 20, 0)
	formation_mark.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	formation_mark.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	formation_mark.add_theme_font_size_override("font_size", 8)
	formation_mark.add_theme_color_override("font_color", Color.YELLOW)
	formation_mark.text = "阵"
	formation_mark.visible = false
	slot_container.add_child(formation_mark)
	
	# 连接输入事件
	slot_container.gui_input.connect(_on_beast_slot_input.bind(index))
	slot_container.mouse_entered.connect(_on_beast_slot_mouse_entered.bind(slot_container, index))
	slot_container.mouse_exited.connect(_on_beast_slot_mouse_exited)
	
	return slot_container

func _create_formation_slot(index: int) -> Control:
	"""创建队伍编成槽位"""
	var slot_container = Control.new()
	slot_container.custom_minimum_size = Vector2(200, 80)
	slot_container.size = Vector2(200, 80)
	
	# 创建背景面板
	var background = Panel.new()
	background.size = Vector2(200, 80)
	background.anchors_preset = Control.PRESET_FULL_RECT
	
	# 创建样式
	var style_box = StyleBoxFlat.new()
	style_box.bg_color = Color(0.2, 0.2, 0.3, 0.9)  # 深蓝色背景
	style_box.border_width_left = 2
	style_box.border_width_right = 2
	style_box.border_width_top = 2
	style_box.border_width_bottom = 2
	style_box.border_color = Color(0.6, 0.6, 0.8, 1.0)  # 蓝灰色边框
	style_box.corner_radius_top_left = 5
	style_box.corner_radius_top_right = 5
	style_box.corner_radius_bottom_left = 5
	style_box.corner_radius_bottom_right = 5
	background.add_theme_stylebox_override("panel", style_box)
	slot_container.add_child(background)
	
	# 创建幻兽图标
	var beast_icon = TextureRect.new()
	beast_icon.name = "BeastIcon"
	beast_icon.size = Vector2(60, 60)
	beast_icon.position = Vector2(10, 10)
	beast_icon.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
	beast_icon.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	beast_icon.visible = false
	slot_container.add_child(beast_icon)
	
	# 创建文本标签
	var text_label = Label.new()
	text_label.name = "TextLabel"
	text_label.size = Vector2(120, 60)
	text_label.position = Vector2(75, 10)
	text_label.text = "空槽位 %d" % (index + 1)
	text_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	text_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	text_label.add_theme_font_size_override("font_size", 12)
	text_label.add_theme_color_override("font_color", Color.WHITE)
	text_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	slot_container.add_child(text_label)
	
	# 连接输入事件
	slot_container.gui_input.connect(_on_formation_slot_input.bind(index))
	slot_container.mouse_entered.connect(_on_formation_slot_mouse_entered.bind(slot_container, index))
	slot_container.mouse_exited.connect(_on_formation_slot_mouse_exited)
	
	return slot_container

func refresh_beast_grid():
	"""刷新幻兽格子显示"""
	if PhantomBeastManager == null:
		return
	
	current_beasts = PhantomBeastManager.get_all_owned_beasts()
	active_formation = PhantomBeastManager.get_active_formation_ids()
	
	# 清空所有格子数据
	for i in range(MAX_BEAST_SLOTS):
		beast_slot_data[i] = {}
	
	# 填充幻兽到格子中
	for i in range(min(current_beasts.size(), MAX_BEAST_SLOTS)):
		beast_slot_data[i] = current_beasts[i]
	
	# 更新所有格子的显示
	for i in range(MAX_BEAST_SLOTS):
		_update_beast_slot_display(i)
	
	# 如果没有幻兽，清空信息面板
	if current_beasts.size() == 0:
		_clear_beast_info()
		formation_button.disabled = true
		sell_button.disabled = true

func refresh_beast_grid_with_sorted_data(sorted_beasts: Array[Dictionary]):
	"""使用排序后的数据刷新幻兽格子显示"""
	if PhantomBeastManager == null:
		return
	
	current_beasts = sorted_beasts
	active_formation = PhantomBeastManager.get_active_formation_ids()
	
	# 清空所有格子数据
	for i in range(MAX_BEAST_SLOTS):
		beast_slot_data[i] = {}
	
	# 填充排序后的幻兽到格子中
	for i in range(min(current_beasts.size(), MAX_BEAST_SLOTS)):
		beast_slot_data[i] = current_beasts[i]
	
	# 更新所有格子的显示
	for i in range(MAX_BEAST_SLOTS):
		_update_beast_slot_display(i)
	
	# 如果没有幻兽，清空信息面板
	if current_beasts.size() == 0:
		_clear_beast_info()
		formation_button.disabled = true
		sell_button.disabled = true

func _update_beast_slot_display(index: int):
	"""更新单个幻兽格子的显示"""
	if index >= beast_slots.size():
		return
	
	var slot_ui = beast_slots[index]
	var beast_data = beast_slot_data[index]
	var beast_icon = slot_ui.get_node("BeastIcon")
	var level_label = slot_ui.get_node("LevelLabel")
	var star_label = slot_ui.get_node("StarLabel")
	var formation_mark = slot_ui.get_node("FormationMark")
	
	# 检查是否被选中用于卖出
	var is_selected_for_sale = _is_beast_selected_for_sale(index)
	_update_beast_slot_visual(slot_ui, is_selected_for_sale)
	
	if beast_data.has("unique_id") and beast_data.unique_id != "":
		# 有幻兽数据，显示幻兽
		beast_icon.visible = true
		level_label.visible = true
		
		# 加载幻兽图标（如果没有图标路径，使用默认SVG）
		var icon_path = beast_data.get("icon_path", beast_data.get("sprite_path", ""))
		if icon_path != "" and ResourceLoader.exists(icon_path):
			beast_icon.texture = load(icon_path)
		else:
			# 创建简单的SVG图标
			beast_icon.texture = _create_default_beast_icon()
		
		# 根据生命值状态设置图标颜色
		var is_alive = beast_data.get("is_alive", true)
		var current_hp = beast_data.get("current_hp", beast_data.stats.max_hp)
		var max_hp = beast_data.stats.max_hp
		var hp_percentage = float(current_hp) / float(max_hp) if max_hp > 0 else 0.0
		
		if not is_alive:
			# 死亡状态：灰色
			beast_icon.modulate = Color(0.5, 0.5, 0.5, 1.0)
		elif hp_percentage <= 0.3:
			# 低血量：红色调
			beast_icon.modulate = Color(1.0, 0.6, 0.6, 1.0)
		elif hp_percentage <= 0.6:
			# 中等血量：黄色调
			beast_icon.modulate = Color(1.0, 1.0, 0.7, 1.0)
		else:
			# 健康状态：正常颜色
			beast_icon.modulate = Color.WHITE
		
		# 显示等级
		level_label.text = str(beast_data.level)
		
		# 显示星级
		var star_level = beast_data.get("star_level", 1)
		if star_level > 1:
			var star_text = ""
			for i in range(star_level):
				star_text += "★"
			star_label.text = star_text
			star_label.visible = true
		else:
			star_label.visible = false
		
		# 显示上阵标记
		if beast_data.unique_id in active_formation:
			formation_mark.visible = true
		else:
			formation_mark.visible = false
	else:
		# 空格子
		beast_icon.visible = false
		level_label.visible = false
		star_label.visible = false
		formation_mark.visible = false

func _is_beast_selected_for_sale(index: int) -> bool:
	"""检查幻兽是否被选中用于卖出"""
	for beast_info in selected_beasts_for_sale:
		if beast_info.index == index:
			return true
	return false

func _update_beast_slot_visual(slot_ui: Control, is_selected: bool):
	"""更新幻兽格子的视觉效果"""
	var background = slot_ui.get_child(0) as Panel
	if background:
		if is_selected:
			# 选中状态 - 蓝色边框
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)
			style_box.border_width_left = 3
			style_box.border_width_right = 3
			style_box.border_width_top = 3
			style_box.border_width_bottom = 3
			style_box.border_color = Color(0.2, 0.6, 1.0, 1.0)  # 蓝色边框
			style_box.corner_radius_top_left = 3
			style_box.corner_radius_top_right = 3
			style_box.corner_radius_bottom_left = 3
			style_box.corner_radius_bottom_right = 3
			background.add_theme_stylebox_override("panel", style_box)
		else:
			# 未选中状态 - 恢复原始样式
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)
			style_box.border_width_left = 1
			style_box.border_width_right = 1
			style_box.border_width_top = 1
			style_box.border_width_bottom = 1
			style_box.border_color = Color(0.5, 0.5, 0.5, 1.0)
			style_box.corner_radius_top_left = 3
			style_box.corner_radius_top_right = 3
			style_box.corner_radius_bottom_left = 3
			style_box.corner_radius_bottom_right = 3
			background.add_theme_stylebox_override("panel", style_box)

func _toggle_beast_selection(index: int):
	"""切换幻兽的选中状态（多选模式）"""
	if index < 0 or index >= beast_slot_data.size():
		return
	
	var beast_data = beast_slot_data[index]
	if not beast_data.has("unique_id") or beast_data.unique_id == "":
		return
	
	# 检查是否已经选中
	var is_selected = false
	var selected_index = -1
	for i in range(selected_beasts_for_sale.size()):
		if selected_beasts_for_sale[i].index == index:
			is_selected = true
			selected_index = i
			break
	
	if is_selected:
		# 取消选中
		selected_beasts_for_sale.remove_at(selected_index)
		# 如果取消选中后还有其他选中的幻兽，显示最后一个选中的幻兽信息
		if selected_beasts_for_sale.size() > 0:
			var last_selected = selected_beasts_for_sale[selected_beasts_for_sale.size() - 1]
			_select_beast(last_selected.index)
		else:
			# 没有选中的幻兽了，清空信息显示
			_clear_beast_info()
			_clear_highlight()
			formation_button.disabled = true
			sell_button.disabled = true
			revive_button.disabled = true
			revive_button.visible = false
	else:
		# 添加到选中列表
		selected_beasts_for_sale.append({
			"index": index,
			"unique_id": beast_data.unique_id,
			"data": beast_data
		})
		# 显示最后选中的幻兽详细信息
		_select_beast(index)
	
	# 更新UI显示
	_update_beast_slot_display(index)
	_update_batch_sell_button()

func _clear_beast_selection():
	"""清空幻兽多选状态"""
	var old_selected = selected_beasts_for_sale.duplicate()
	selected_beasts_for_sale.clear()
	
	# 更新之前选中的格子显示
	for beast_info in old_selected:
		_update_beast_slot_display(beast_info.index)
	
	_update_batch_sell_button()

func _update_batch_sell_button():
	"""更新批量卖出按钮状态"""
	if selected_beasts_for_sale.size() > 0:
		batch_sell_button.disabled = false
		batch_sell_button.text = "卖出选中 (%d)" % selected_beasts_for_sale.size()
	else:
		batch_sell_button.disabled = true
		batch_sell_button.text = "批量卖出"

func _on_select_all_button_pressed():
	"""全选按钮点击处理"""
	if selected_beasts_for_sale.size() == 0:
		# 当前没有选中任何幻兽，执行全选
		for i in range(beast_slot_data.size()):
			var beast_data = beast_slot_data[i]
			if beast_data.has("unique_id") and beast_data.unique_id != "":
				# 检查幻兽是否在队伍中，在队伍中的不能卖出
				if not (beast_data.unique_id in active_formation):
					selected_beasts_for_sale.append({
						"index": i,
						"unique_id": beast_data.unique_id,
						"data": beast_data
					})
					_update_beast_slot_display(i)
		select_all_button.text = "取消全选"
	else:
		# 当前有选中的幻兽，执行取消全选
		_clear_beast_selection()
		select_all_button.text = "全选"
	
	_update_batch_sell_button()

func _on_batch_sell_button_pressed():
	"""批量卖出按钮点击处理"""
	if selected_beasts_for_sale.size() == 0:
		return
	
	# 计算总价值
	var total_price = 0
	for beast_info in selected_beasts_for_sale:
		total_price += _calculate_sell_price(beast_info.data)
	
	# 显示确认对话框
	var confirmation_text = "确定要卖出选中的 %d 只幻兽吗？\n总价值：%d 金币" % [selected_beasts_for_sale.size(), total_price]
	
	# 创建确认对话框
	var dialog = AcceptDialog.new()
	dialog.dialog_text = confirmation_text
	dialog.title = "确认卖出"
	dialog.add_cancel_button("取消")
	get_tree().current_scene.add_child(dialog)
	dialog.popup_centered()
	
	# 连接确认信号
	dialog.confirmed.connect(_execute_batch_sell)
	dialog.tree_exited.connect(func(): dialog.queue_free())

func _execute_batch_sell():
	"""执行批量卖出"""
	var total_price = 0
	var sold_beasts = []
	
	# 按索引倒序排列，避免删除时索引错乱
	selected_beasts_for_sale.sort_custom(func(a, b): return a.index > b.index)
	
	for beast_info in selected_beasts_for_sale:
		var beast_id = beast_info.unique_id
		var sell_price = _calculate_sell_price(beast_info.data)
		
		if PhantomBeastManager.sell_phantom_beast(beast_id):
			total_price += sell_price
			sold_beasts.append(beast_info.data.name)
	
	if sold_beasts.size() > 0:
		print("批量卖出成功：%s，获得 %d 金币" % [" ".join(sold_beasts), total_price])
		
		# 保存游戏数据
		GameSaveManager.save_game_to_slot(GameSaveManager.current_save_slot)
		
		# 清空选择并刷新显示
		_clear_beast_selection()
		refresh_beast_grid()
		update_gold_display()
		
		# 重置按钮文本
		select_all_button.text = "全选"
		
		# 清空当前选中的幻兽信息
		_clear_beast_info()
		_clear_highlight()
		formation_button.disabled = true
		sell_button.disabled = true
		revive_button.disabled = true
		revive_button.visible = false
	else:
		print("批量卖出失败")

func _create_default_beast_icon() -> ImageTexture:
	"""创建默认的幻兽图标SVG"""
	var svg_content = '''
<svg width="64" height="64" xmlns="http://www.w3.org/2000/svg">
  <rect width="64" height="64" fill="#4a4a4a" stroke="#888" stroke-width="2" rx="8"/>
  <circle cx="20" cy="20" r="4" fill="#ff6b6b"/>
  <circle cx="44" cy="20" r="4" fill="#ff6b6b"/>
  <path d="M16 40 Q32 50 48 40" stroke="#ff6b6b" stroke-width="3" fill="none"/>
  <text x="32" y="55" text-anchor="middle" fill="#fff" font-size="8">兽</text>
</svg>
'''
	
	var image = Image.new()
	image.load_svg_from_string(svg_content)
	var texture = ImageTexture.new()
	texture.set_image(image)
	return texture

func _clear_beast_info():
	"""清空幻兽信息显示"""
	beast_name_label.text = "暂无幻兽"
	beast_level_label.text = ""
	beast_stats_label.text = ""
	beast_description_label.text = ""
	selected_beast_id = ""
	selected_slot_index = -1
	# 隐藏复活按钮
	revive_button.visible = false
	revive_button.disabled = true

func refresh_formation_display():
	"""刷新队伍编成显示"""
	if PhantomBeastManager == null:
		return
	
	active_formation = PhantomBeastManager.get_active_formation_ids()
	
	for i in range(formation_slots.size()):
		var slot_ui = formation_slots[i]
		var beast_icon = slot_ui.get_node("BeastIcon")
		var text_label = slot_ui.get_node("TextLabel")
		
		if i < active_formation.size() and active_formation[i] != "":
			var beast = PhantomBeastManager.get_beast_by_id(active_formation[i])
			if beast != null and not beast.is_empty() and beast.has("name") and beast.has("level"):
				# 显示幻兽信息（使用显示名称）
				var display_name = PhantomBeastManager.get_phantom_beast_display_name(active_formation[i])
				text_label.text = "%s\nLv.%d" % [display_name, beast.level]
				beast_icon.visible = true
				
				# 加载幻兽图标
				var icon_path = beast.get("icon_path", beast.get("sprite_path", ""))
				if icon_path != "" and ResourceLoader.exists(icon_path):
					beast_icon.texture = load(icon_path)
				else:
					beast_icon.texture = _create_default_beast_icon()
			else:
				text_label.text = "空槽位 %d" % (i + 1)
				beast_icon.visible = false
		else:
			text_label.text = "空槽位 %d" % (i + 1)
			beast_icon.visible = false



func _on_beast_slot_input(event: InputEvent, index: int):
	"""幻兽格子输入处理"""
	if event is InputEventMouseButton:
		var beast_data = beast_slot_data[index]
		var slot_ui = beast_slots[index]
		
		if event.button_index == MOUSE_BUTTON_LEFT:
			if event.pressed:
				# 检测双击
				var current_time = Time.get_ticks_msec() / 1000.0
				var is_double_click = false
				
				if last_click_slot == slot_ui and (current_time - last_click_time) < double_click_threshold:
					# 双击检测成功
					is_double_click = true
					last_click_slot = null  # 重置，避免三击被误认为双击
					if beast_data.has("unique_id") and beast_data.unique_id != "":
						# 双击有幻兽的格子：加入/退出队伍
						_toggle_formation(beast_data.unique_id)
				else:
					# 记录单击信息
					last_click_time = current_time
					last_click_slot = slot_ui
				
				if not is_double_click:
					# 鼠标按下，开始计时（非双击情况）
					mouse_press_time = current_time
					mouse_press_slot = slot_ui
					is_mouse_pressed = true
			else:
				# 鼠标释放，判断是单击还是拖拽
				if is_mouse_pressed and mouse_press_slot == slot_ui and not is_dragging:
					var press_duration = (Time.get_ticks_msec() / 1000.0) - mouse_press_time
					
					if press_duration < DRAG_THRESHOLD_TIME:
						# 短按：直接进行多选操作
						if beast_data.has("unique_id") and beast_data.unique_id != "":
							# 点击幻兽：多选模式
							_toggle_beast_selection(index)
						else:
							# 点击空格子，清空选择和高亮
							_clear_beast_info()
							_clear_highlight()
							formation_button.disabled = true
							sell_button.disabled = true
							revive_button.disabled = true
							revive_button.visible = false
							# 清空多选
							_clear_beast_selection()
						# 长按拖拽在_process中处理
				
				# 重置按压状态
				is_mouse_pressed = false
				mouse_press_slot = null
		elif event.button_index == MOUSE_BUTTON_RIGHT and event.pressed:
			# 右键：选中幻兽或清空选择
			if beast_data.has("unique_id") and beast_data.unique_id != "":
				_select_and_highlight_beast(index)
			else:
				_clear_beast_info()
				_clear_highlight()
				formation_button.disabled = true
				sell_button.disabled = true
				revive_button.disabled = true
				revive_button.visible = false

func _on_beast_slot_mouse_entered(slot_ui: Control, _index: int):
	"""鼠标进入幻兽格子"""
	if is_dragging:
		# 拖拽时高亮目标格子
		var background = slot_ui.get_child(0) as Panel
		if background:
			var style_box = background.get_theme_stylebox("panel").duplicate() as StyleBoxFlat
			style_box.border_color = Color.YELLOW
			style_box.border_width_left = 2
			style_box.border_width_right = 2
			style_box.border_width_top = 2
			style_box.border_width_bottom = 2
			background.add_theme_stylebox_override("panel", style_box)

func _on_beast_slot_mouse_exited():
	"""鼠标离开幻兽格子"""
	pass  # 在拖拽结束时统一恢复样式

func _on_formation_slot_input(event: InputEvent, index: int):
	"""队伍槽位输入处理"""
	if event is InputEventMouseButton:
		var formation_slot_ui = formation_slots[index]
		
		if event.button_index == MOUSE_BUTTON_LEFT:
			if event.pressed:
				# 检测双击
				var current_time = Time.get_ticks_msec() / 1000.0
				var is_double_click = false
				
				if last_click_slot == formation_slot_ui and (current_time - last_click_time) < double_click_threshold:
					# 双击检测成功
					is_double_click = true
					last_click_slot = null  # 重置，避免三击被误认为双击
					if index < active_formation.size() and active_formation[index] != "":
						# 双击有幻兽的队伍槽位：移除幻兽
						PhantomBeastManager.remove_from_formation(active_formation[index])
						print("双击：幻兽已从槽位 %d 移除" % (index + 1))
						
						# 保存游戏数据
						GameSaveManager.save_game_to_slot(GameSaveManager.current_save_slot)
						
						# 自动整理背包
						_auto_sort_beasts()
						
						refresh_beast_grid()
						refresh_formation_display()
			
						# 刷新当前选中幻兽的显示
						if selected_slot_index >= 0:
							_select_and_highlight_beast(selected_slot_index)
				else:
					# 记录单击信息
					last_click_time = current_time
					last_click_slot = formation_slot_ui
				
				if not is_double_click:
					# 鼠标按下，开始计时（非双击情况）
					mouse_press_time = current_time
					mouse_press_slot = formation_slot_ui
					is_mouse_pressed = true
			else:
				# 鼠标释放，判断是单击还是拖拽
				if is_mouse_pressed and mouse_press_slot == formation_slot_ui and not is_dragging:
					var press_duration = (Time.get_ticks_msec() / 1000.0) - mouse_press_time
					
					if press_duration < DRAG_THRESHOLD_TIME:
						# 短按：单击处理
						if index < active_formation.size() and active_formation[index] != "":
							# 单击有幻兽的队伍槽位：选中并高亮该幻兽
							var formation_beast_id = active_formation[index]
							# 在幻兽格子中找到对应的幻兽并选中
							for i in range(beast_slot_data.size()):
								var beast_data = beast_slot_data[i]
								if beast_data.has("unique_id") and beast_data.unique_id == formation_beast_id:
									_select_and_highlight_beast(i)
									break
						else:
							# 单击空槽位：如果有选中的幻兽且不在队伍中，则加入队伍
							if selected_beast_id != "" and not (selected_beast_id in active_formation):
								var slot_success = PhantomBeastManager.add_to_formation(selected_beast_id)
								if slot_success:
									print("单击：幻兽已加入槽位 %d" % (index + 1))
									
									# 保存游戏数据
									GameSaveManager.save_game_to_slot(GameSaveManager.current_save_slot)
									
									# 自动整理背包
									_auto_sort_beasts()
									
									refresh_beast_grid()
									refresh_formation_display()
					
									# 刷新当前选中幻兽的显示
									if selected_slot_index >= 0:
										_select_and_highlight_beast(selected_slot_index)
								else:
									print("队伍已满，无法加入更多幻兽")
							# 长按拖拽在_process中处理
				
				# 重置按压状态
				is_mouse_pressed = false
				mouse_press_slot = null
		elif event.button_index == MOUSE_BUTTON_RIGHT and event.pressed:
			# 右键：选中幻兽或清空选择
			if index < active_formation.size() and active_formation[index] != "":
				# 右键有幻兽的队伍槽位：选中并高亮该幻兽
				var formation_beast_id = active_formation[index]
				# 在幻兽格子中找到对应的幻兽并选中
				for i in range(beast_slot_data.size()):
					var beast_data = beast_slot_data[i]
					if beast_data.has("unique_id") and beast_data.unique_id == formation_beast_id:
						_select_and_highlight_beast(i)
						break
			else:
				_clear_beast_info()
				_clear_highlight()
				formation_button.disabled = true
				sell_button.disabled = true

func _on_formation_slot_mouse_entered(slot_ui: Control, _index: int):
	"""鼠标进入队伍槽位"""
	if is_dragging:
		# 拖拽时高亮目标槽位
		var background = slot_ui.get_child(0) as Panel
		if background:
			var style_box = background.get_theme_stylebox("panel").duplicate() as StyleBoxFlat
			style_box.border_color = Color.YELLOW
			style_box.border_width_left = 3
			style_box.border_width_right = 3
			style_box.border_width_top = 3
			style_box.border_width_bottom = 3
			background.add_theme_stylebox_override("panel", style_box)

func _on_formation_slot_mouse_exited():
	"""鼠标离开队伍槽位"""
	pass  # 在拖拽结束时统一恢复样式

func _select_beast(index: int):
	"""选中幻兽"""
	if index < 0 or index >= beast_slot_data.size():
		return
	
	var beast_data = beast_slot_data[index]
	if not beast_data.has("unique_id") or beast_data.unique_id == "":
		return
	
	selected_beast_id = beast_data.unique_id
	selected_slot_index = index
	
	# 更新幻兽信息显示
	var star_level = int(beast_data.get("star_level", 1))
	var star_text = ""
	if star_level > 1:
		for i in range(star_level):
			star_text += "★"
	
	# 显示幻兽名称（优先显示昵称）
	var display_name = beast_data.name
	var custom_name = beast_data.get("custom_name", "")
	if custom_name != "":
		display_name = custom_name
	beast_name_label.text = display_name + (" " + star_text if star_text != "" else "")
	beast_level_label.text = "等级: %d" % beast_data.level
	
	# 更新经验显示
	var current_exp = beast_data.get("current_exp", 0)
	var next_level_exp = 0
	if PhantomBeastManager != null and beast_data.level < PhantomBeastManager.max_phantom_beast_level:
		next_level_exp = PhantomBeastManager.level_exp_requirements[beast_data.level]
	else:
		next_level_exp = current_exp  # 满级时显示当前经验
	
	if beast_data.level >= PhantomBeastManager.max_phantom_beast_level:
		beast_exp_label.text = "经验: MAX"
	else:
		beast_exp_label.text = "经验: %d/%d" % [current_exp, next_level_exp]
	
	# 更新昵称输入框
	nickname_line_edit.text = custom_name
	nickname_line_edit.placeholder_text = beast_data.name
	
	# 获取实时生命值信息
	var current_hp = beast_data.get("current_hp", beast_data.stats.max_hp)
	var max_hp = beast_data.stats.max_hp
	var is_alive = beast_data.get("is_alive", true)
	
	# 根据生存状态和生命值百分比设置显示颜色
	var hp_percentage = float(current_hp) / float(max_hp) if max_hp > 0 else 0.0
	var hp_color = "[color=red]" # 默认红色（死亡或低血量）
	if is_alive:
		if hp_percentage > 0.6:
			hp_color = "[color=green]" # 绿色（健康）
		elif hp_percentage > 0.3:
			hp_color = "[color=yellow]" # 黄色（中等血量）
		else:
			hp_color = "[color=orange]" # 橙色（低血量）
	
	var hp_text = "%s%d/%d[/color]" % [hp_color, current_hp, max_hp]
	if not is_alive:
		hp_text += " [color=gray](已死亡)[/color]"
	
	# 计算卖出价格和复活费用
	var sell_price = _calculate_sell_price(beast_data)
	var revive_cost = _calculate_revive_cost(beast_data)
	
	var stats_text = "攻击力: %d\n防御力: %d\n生命值: %s\n\n[color=yellow]卖出价格: %d 金币[/color]" % [
		beast_data.stats.attack,
		beast_data.stats.defense,
		hp_text,
		sell_price
	]
	
	# 如果幻兽已死亡，显示复活费用
	if not is_alive:
		stats_text += "\n[color=cyan]复活费用: %d 金币[/color]" % revive_cost
		revive_button.visible = true
		revive_button.disabled = false
	else:
		revive_button.visible = false
		revive_button.disabled = true
	
	beast_stats_label.text = stats_text
	beast_description_label.text = beast_data.get("description", "")
	
	# 更新按钮状态
	formation_button.disabled = false
	sell_button.disabled = false
	
	# 更新编成按钮文本
	if selected_beast_id in active_formation:
		formation_button.text = "退出队伍"
	else:
		formation_button.text = "加入队伍"
	
	# 显示合成界面
	_update_synthesis_display()

func _select_and_highlight_beast(index: int):
	"""选中并高亮幻兽"""
	_select_beast(index)
	_highlight_beast_slot(index)

func _highlight_beast_slot(index: int):
	"""高亮指定的幻兽格子"""
	# 清除之前的高亮
	_clear_highlight()
	
	if index < 0 or index >= beast_slots.size():
		return
	
	var slot_ui = beast_slots[index]
	var background = slot_ui.get_child(0) as Panel
	if background:
		var style_box = background.get_theme_stylebox("panel").duplicate() as StyleBoxFlat
		style_box.border_color = Color.CYAN
		style_box.border_width_left = 3
		style_box.border_width_right = 3
		style_box.border_width_top = 3
		style_box.border_width_bottom = 3
		background.add_theme_stylebox_override("panel", style_box)
		highlighted_slot = slot_ui

func _clear_highlight():
	"""清除高亮显示"""
	if highlighted_slot != null:
		var background = highlighted_slot.get_child(0) as Panel
		if background:
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)
			style_box.border_width_left = 1
			style_box.border_width_right = 1
			style_box.border_width_top = 1
			style_box.border_width_bottom = 1
			style_box.border_color = Color(0.5, 0.5, 0.5, 1.0)
			style_box.corner_radius_top_left = 3
			style_box.corner_radius_top_right = 3
			style_box.corner_radius_bottom_left = 3
			style_box.corner_radius_bottom_right = 3
			background.add_theme_stylebox_override("panel", style_box)
		highlighted_slot = null

func _toggle_formation(beast_id: String):
	"""切换幻兽的队伍状态"""
	if PhantomBeastManager == null:
		return
	
	var is_in_formation = beast_id in active_formation
	
	if is_in_formation:
		# 从队伍中移除
		PhantomBeastManager.remove_from_formation(beast_id)
		print("双击：幻兽已从队伍中移除")
	else:
		# 加入队伍
		var formation_success = PhantomBeastManager.add_to_formation(beast_id)
		if formation_success:
			print("双击：幻兽已加入队伍")
		else:
			print("队伍已满，无法加入更多幻兽")
	
	# 保存游戏数据
	GameSaveManager.save_game_to_slot(GameSaveManager.current_save_slot)
	
	# 刷新显示
	refresh_beast_grid()
	refresh_formation_display()
	
	# 如果当前有选中的幻兽，刷新其显示
	if selected_slot_index >= 0:
		_select_beast(selected_slot_index)

func _on_formation_button_pressed():
	"""编成按钮点击处理"""
	if selected_beast_id == "" or PhantomBeastManager == null:
		return
	
	var is_in_formation = selected_beast_id in active_formation
	
	if is_in_formation:
		# 从队伍中移除
		PhantomBeastManager.remove_from_formation(selected_beast_id)
		print("幻兽已从队伍中移除")
	else:
		# 加入队伍
		var formation_success = PhantomBeastManager.add_to_formation(selected_beast_id)
		if formation_success:
			print("幻兽已加入队伍")
		else:
			print("队伍已满，无法加入更多幻兽")
	
	# 保存游戏数据
	GameSaveManager.save_game_to_slot(GameSaveManager.current_save_slot)
	
	# 刷新显示
	refresh_beast_grid()
	refresh_formation_display()
	
	# 刷新当前选中幻兽的显示
	if selected_slot_index >= 0:
		_select_beast(selected_slot_index)

func _on_sell_button_pressed():
	"""卖出按钮点击处理"""
	if selected_beast_id == "" or PhantomBeastManager == null:
		return
	
	# 获取幻兽数据
	var beast_data = PhantomBeastManager.get_beast_by_id(selected_beast_id)
	if beast_data == null or beast_data.is_empty():
		return
	
	# 计算卖出价格
	var sell_price = _calculate_sell_price(beast_data)
	
	# 确认对话框
	var confirmation_dialog = AcceptDialog.new()
	confirmation_dialog.dialog_text = "确定要卖出 %s 吗？\n你将获得 %d 金币。" % [beast_data.name, sell_price]
	confirmation_dialog.title = "确认卖出"
	confirmation_dialog.add_cancel_button("取消")
	add_child(confirmation_dialog)
	
	# 连接确认信号
	confirmation_dialog.confirmed.connect(_confirm_sell_beast.bind(selected_beast_id, sell_price))
	confirmation_dialog.popup_centered()

func _confirm_sell_beast(beast_id: String, sell_price: int):
	"""确认卖出幻兽"""
	if PhantomBeastManager == null or PlayerStatsManager == null:
		return
	
	# 从队伍中移除（如果在队伍中）
	if beast_id in active_formation:
		PhantomBeastManager.remove_from_formation(beast_id)
	
	# 卖出幻兽（PhantomBeastManager会自动处理金币添加）
	var sell_success = PhantomBeastManager.sell_phantom_beast(beast_id)
	if sell_success:
		print("幻兽已卖出，获得 %d 金币" % sell_price)
		
		# 保存游戏数据
		GameSaveManager.save_game_to_slot(GameSaveManager.current_save_slot)
		
		# 清空选择
		_clear_beast_info()
		_clear_highlight()
		formation_button.disabled = true
		sell_button.disabled = true
		revive_button.disabled = true
		revive_button.visible = false
		
		# 刷新显示
		refresh_beast_grid()
		refresh_formation_display()
	else:
		print("卖出失败")

func _on_revive_button_pressed():
	"""复活按钮点击处理"""
	if selected_beast_id == "" or PhantomBeastManager == null or PlayerStatsManager == null:
		return
	
	# 获取幻兽数据
	var beast_data = PhantomBeastManager.get_beast_by_id(selected_beast_id)
	if beast_data == null or beast_data.is_empty():
		return
	
	# 检查幻兽是否已死亡
	var is_alive = beast_data.get("is_alive", true)
	if is_alive:
		print("幻兽还活着，无需复活")
		return
	
	# 计算复活费用
	var revive_cost = _calculate_revive_cost(beast_data)
	
	# 检查金币是否足够
	var current_gold = PlayerStatsManager.get_gold()
	if current_gold < revive_cost:
		print("金币不足，无法复活幻兽")
		return
	
	# 确认对话框
	var confirmation_dialog = AcceptDialog.new()
	confirmation_dialog.dialog_text = "确定要复活 %s 吗？\n需要花费 %d 金币。" % [beast_data.name, revive_cost]
	confirmation_dialog.title = "确认复活"
	confirmation_dialog.add_cancel_button("取消")
	add_child(confirmation_dialog)
	
	# 连接确认信号
	confirmation_dialog.confirmed.connect(_confirm_revive_beast.bind(selected_beast_id, revive_cost))
	confirmation_dialog.popup_centered()

func _confirm_revive_beast(beast_id: String, revive_cost: int):
	"""确认复活幻兽"""
	if PhantomBeastManager == null or PlayerStatsManager == null:
		return
	
	# 扣除金币
	PlayerStatsManager.spend_gold(revive_cost)
	
	# 复活幻兽
	var revive_success = PhantomBeastManager.revive_phantom_beast(beast_id)
	if revive_success:
		# 保存游戏数据
		GameSaveManager.save_game_to_slot(GameSaveManager.current_save_slot)
		
		# 刷新显示
		refresh_beast_grid()
		
		# 刷新当前选中幻兽的显示
		if selected_slot_index >= 0:
			_select_and_highlight_beast(selected_slot_index)
	else:
		print("复活失败")
		# 如果复活失败，退还金币
		PlayerStatsManager.add_gold(revive_cost)

func _calculate_sell_price(beast_data: Dictionary) -> int:
	"""计算幻兽卖出价格"""
	# 直接使用PhantomBeastManager的计算函数确保一致性
	var beast_id = beast_data.get("unique_id", "")
	if beast_id != "" and PhantomBeastManager != null:
		return PhantomBeastManager.calculate_sell_price(beast_id)
	return 0

func _calculate_revive_cost(beast_data: Dictionary) -> int:
	"""计算幻兽复活费用"""
	# 直接使用PhantomBeastManager的计算函数确保一致性
	var beast_id = beast_data.get("unique_id", "")
	if beast_id != "" and PhantomBeastManager != null:
		return PhantomBeastManager.calculate_revive_cost(beast_id)
	return 0

func _on_close_button_pressed():
	"""关闭按钮点击处理"""
	hide()

func _on_nickname_button_pressed():
	"""昵称修改按钮点击处理"""
	if selected_beast_id == "" or PhantomBeastManager == null:
		return
	
	var new_nickname = nickname_line_edit.text.strip_edges()
	
	# 调用幻兽管理器的昵称修改功能
	if PhantomBeastManager.has_method("set_phantom_beast_nickname"):
		PhantomBeastManager.set_phantom_beast_nickname(selected_beast_id, new_nickname)
		print("幻兽昵称已修改为: %s" % (new_nickname if new_nickname != "" else "[默认名称]"))
		
		# 保存游戏数据
		GameSaveManager.save_game_to_slot(GameSaveManager.current_save_slot)
		
		# 刷新显示
		refresh_beast_grid()
		if selected_slot_index >= 0:
			_select_beast(selected_slot_index)
	else:
		print("错误：幻兽管理器不支持昵称修改功能")

func update_gold_display():
	"""更新金币显示"""
	if PlayerStatsManager != null and gold_label != null:
		var current_gold = PlayerStatsManager.get_gold()
		gold_label.text = "金币: %d" % current_gold

func _on_gold_changed(new_gold: int):
	"""金币变化时的回调"""
	if gold_label != null:
		gold_label.text = "金币: %d" % new_gold

func _update_synthesis_display():
	"""更新合成界面显示"""
	if synthesis_container == null:
		return
	
	# 合成界面始终可见
	synthesis_container.visible = true
	
	if selected_beast_id == "":
		# 没有选中主宠时的显示
		synthesis_info_label.text = "请先选择一个幻兽作为主宠，然后拖拽同类型同星级的副宠到下方槽位进行合成"
		synthesis_button.disabled = true
		synthesis_button.text = "合成"
		return
	
	var beast_data = PhantomBeastManager.get_beast_by_id(selected_beast_id)
	if beast_data == null or beast_data.is_empty():
		synthesis_info_label.text = "选中的幻兽数据无效"
		synthesis_button.disabled = true
		return
	
	var star_level = beast_data.get("star_level", 1)
	var is_alive = beast_data.get("is_alive", true)
	
	# 检查是否可以合成
	if not is_alive:
		synthesis_info_label.text = "死亡的幻兽无法进行合成，请先复活"
		synthesis_button.disabled = true
		return
	
	if star_level >= PhantomBeastManager.max_star_level:
		synthesis_info_label.text = "该幻兽已达到最高星级，无法继续合成"
		synthesis_button.disabled = true
		return
	
	# 更新合成信息
	var synthesis_cost = PhantomBeastManager.calculate_synthesis_cost(star_level)
	var next_star = star_level + 1
	synthesis_info_label.text = "合成到 %d 星需要：\n• 2个同类型 %d 星副宠\n• %d 金币" % [next_star, star_level, synthesis_cost]
	
	# 更新合成按钮状态
	_update_synthesis_button_state()

func _update_synthesis_button_state():
	"""更新合成按钮状态"""
	if selected_beast_id == "" or PhantomBeastManager == null:
		synthesis_button.disabled = true
		return
	
	var check_result = PhantomBeastManager.can_synthesize_beast(selected_beast_id, material_beast_ids)
	synthesis_button.disabled = not check_result["can_synthesize"]
	
	if not check_result["can_synthesize"]:
		synthesis_button.text = "合成 (" + check_result["reason"] + ")"
	else:
		synthesis_button.text = "合成"

func _update_material_slot_display(slot_index: int):
	"""更新副宠槽位显示"""
	if slot_index < 0 or slot_index >= material_slots.size():
		return
	
	var slot_ui = material_slots[slot_index]
	var beast_icon = slot_ui.get_node("BeastIcon") as TextureRect
	var level_label = slot_ui.get_node("LevelLabel") as Label
	var star_label = slot_ui.get_node("StarLabel") as Label
	var hint_label = slot_ui.get_node("HintLabel") as Label
	
	var beast_id = material_beast_ids[slot_index]
	if beast_id == "":
		# 空槽位
		beast_icon.visible = false
		level_label.visible = false
		star_label.visible = false
		hint_label.visible = true
		hint_label.text = "副宠" + str(slot_index + 1)
	else:
		# 有幻兽的槽位
		var beast_data = PhantomBeastManager.get_beast_by_id(beast_id)
		if beast_data != null and not beast_data.is_empty():
			# 加载幻兽图标
			var sprite_path = beast_data.get("sprite_path", "")
			if sprite_path != "" and ResourceLoader.exists(sprite_path):
				beast_icon.texture = load(sprite_path)
			else:
				# 使用默认图标或生成简单图标
				beast_icon.texture = _create_default_beast_icon()
			
			beast_icon.visible = true
			level_label.text = str(beast_data.get("level", 1))
			level_label.visible = true
			
			var star_level = int(beast_data.get("star_level", 1))
			if star_level > 1:
				var star_text = ""
				for i in range(star_level):
					star_text += "★"
				star_label.text = star_text
				star_label.visible = true
			else:
				star_label.visible = false
			
			hint_label.visible = false

func _on_synthesis_button_pressed():
	"""合成按钮点击处理"""
	if selected_beast_id == "" or PhantomBeastManager == null:
		return
	
	# 执行合成
	var success = PhantomBeastManager.synthesize_beast(selected_beast_id, material_beast_ids)
	if success:
		material_beast_ids = ["", ""]
		for i in range(material_slots.size()):
			_update_material_slot_display(i)
		
		# 刷新界面
		refresh_beast_grid()
		_update_synthesis_display()
		update_gold_display()
		
		# 保存游戏数据
		if GameSaveManager != null:
			var current_slot = GameSaveManager.current_save_slot
			if current_slot >= 0:
				GameSaveManager.save_game_to_slot(current_slot)
				print("幻兽合成完成并已保存！")
				# 自动整理背包
				_auto_sort_beasts()
	else:
		print("合成失败！")

func _on_beast_synthesized(beast_id: String, new_star_level: int):
	"""幻兽合成成功处理"""
	print("幻兽合成成功！新星级：", new_star_level)
	# 如果合成的是当前选中的幻兽，刷新显示
	if beast_id == selected_beast_id:
		_select_beast(selected_slot_index)

func _on_beast_obtained(beast_data: Dictionary):
	"""获得新幻兽时的处理"""
	refresh_beast_grid()
	print("获得新幻兽: %s" % beast_data.get("name", "未知"))

func _on_beast_level_up(beast_id: String, new_level: int):
	"""幻兽升级时的处理"""
	refresh_beast_grid()
	refresh_formation_display()
	
	# 如果当前选中的幻兽升级了，刷新信息显示
	if selected_beast_id == beast_id and selected_slot_index >= 0:
		_select_beast(selected_slot_index)
	print("幻兽 %s 升级到 %d 级" % [beast_id, new_level])

func _process(_delta):
	"""处理拖拽逻辑"""
	if is_mouse_pressed and mouse_press_slot != null and not is_dragging:
		# 检查是否开始拖拽
		var press_duration = (Time.get_ticks_msec() / 1000.0) - mouse_press_time
		if press_duration >= DRAG_THRESHOLD_TIME:
			# 开始拖拽
			is_dragging = true
			drag_start_slot = mouse_press_slot
			
			# 创建拖拽预览
			_create_drag_preview()
			print("开始拖拽")
	
	if is_dragging:
		# 更新拖拽预览位置
		_update_drag_preview()
		
		# 检查鼠标释放
		if not Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT):
			# 结束拖拽
			_end_drag()

func _create_drag_preview():
	"""创建拖拽预览"""
	if drag_preview != null:
		drag_preview.queue_free()
	
	# 找到被拖拽的幻兽数据
	var dragged_beast_data = null
	var dragged_slot_index = -1
	
	# 检查是否从幻兽格子开始拖拽
	for i in range(beast_slots.size()):
		if beast_slots[i] == drag_start_slot:
			dragged_beast_data = beast_slot_data[i]
			dragged_slot_index = i
			break
	
	if dragged_beast_data == null or not dragged_beast_data.has("unique_id") or dragged_beast_data.unique_id == "":
		return
	
	dragged_beast_id = dragged_beast_data.unique_id
	dragged_from_slot_index = dragged_slot_index
	
	# 创建拖拽预览控件
	drag_preview = Control.new()
	drag_preview.size = Vector2(SLOT_SIZE.x, SLOT_SIZE.y)
	drag_preview.z_index = 1000  # 确保在最上层
	get_viewport().add_child(drag_preview)
	
	# 复制原始图标
	var preview_icon = TextureRect.new()
	preview_icon.size = Vector2(SLOT_SIZE.x - 4, SLOT_SIZE.y - 4)
	preview_icon.position = Vector2(2, 2)
	preview_icon.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
	preview_icon.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	
	# 设置图标纹理
	var icon_path = dragged_beast_data.get("icon_path", "")
	if icon_path != "" and ResourceLoader.exists(icon_path):
		preview_icon.texture = load(icon_path)
	else:
		preview_icon.texture = _create_default_beast_icon()
	
	# 设置半透明效果
	preview_icon.modulate = Color(1, 1, 1, 0.7)
	drag_preview.add_child(preview_icon)

func _update_drag_preview():
	"""更新拖拽预览位置"""
	if drag_preview != null:
		var mouse_pos = get_viewport().get_mouse_position()
		drag_preview.global_position = mouse_pos - Vector2(SLOT_SIZE.x / 2, SLOT_SIZE.y / 2)

func _end_drag():
	"""结束拖拽"""
	if not is_dragging:
		return
	
	is_dragging = false
	is_mouse_pressed = false
	mouse_press_slot = null
	
	# 获取鼠标位置下的控件
	var mouse_pos = get_viewport().get_mouse_position()
	var drop_target = _get_drop_target_at_position(mouse_pos)
	
	if drop_target != null:
		_handle_drop(drop_target)
	
	# 清理拖拽预览
	if drag_preview != null:
		drag_preview.queue_free()
		drag_preview = null
	
	# 恢复所有格子样式
	_restore_all_slot_styles()
	
	dragged_beast_id = ""
	dragged_from_slot_index = -1
	drag_start_slot = null
	print("拖拽结束")

func _get_drop_target_at_position(pos: Vector2) -> Control:
	"""获取指定位置的放置目标"""
	# 检查副宠槽位
	for i in range(material_slots.size()):
		var slot = material_slots[i]
		var slot_rect = Rect2(slot.global_position, slot.size)
		if slot_rect.has_point(pos):
			return slot
	
	# 检查队伍槽位
	for i in range(formation_slots.size()):
		var slot = formation_slots[i]
		var slot_rect = Rect2(slot.global_position, slot.size)
		if slot_rect.has_point(pos):
			return slot
	
	return null

func _handle_drop(drop_target: Control):
	"""处理放置操作"""
	if dragged_beast_id == "":
		return
	
	# 检查是否放置到副宠槽位
	for i in range(material_slots.size()):
		if material_slots[i] == drop_target:
			_handle_material_slot_drop(i)
			return
	
	# 检查是否放置到队伍槽位
	for i in range(formation_slots.size()):
		if formation_slots[i] == drop_target:
			_handle_formation_slot_drop(i)
			return

func _handle_material_slot_drop(slot_index: int):
	"""处理副宠槽位放置"""
	if slot_index < 0 or slot_index >= material_beast_ids.size():
		return
	
	# 检查是否将主宠拖入副宠槽位
	if dragged_beast_id == selected_beast_id:
		print("不能将主宠放入副宠槽位")
		return
	
	var dragged_beast = PhantomBeastManager.get_beast_by_id(dragged_beast_id)
	if dragged_beast == null:
		return
	
	# 如果有选中的主宠，进行兼容性检查
	if selected_beast_id != "":
		var main_beast = PhantomBeastManager.get_beast_by_id(selected_beast_id)
		if main_beast == null:
			return
		
		# 检查类型是否相同
		if dragged_beast.get("monster_type", "") != main_beast.get("monster_type", ""):
			print("副宠类型必须与主宠相同")
			return
		
		# 检查星级是否相同
		var dragged_star = dragged_beast.get("star_level", 1)
		var main_star = main_beast.get("star_level", 1)
		if dragged_star != main_star:
			print("副宠星级必须与主宠相同")
			return
		
		# 检查等级条件
		var dragged_level = dragged_beast.get("level", 1)
		var main_level = main_beast.get("level", 1)
		if main_level < dragged_level:
			print("主宠等级必须大于等于副宠等级")
			return
	
	# 检查是否已经在副宠槽位中
	if dragged_beast_id in material_beast_ids:
		print("该幻兽已在副宠槽位中")
		return
	
	# 检查是否在队伍中
	if dragged_beast_id in active_formation:
		print("队伍中的幻兽不能作为副宠")
		return
	
	# 放置到副宠槽位
	material_beast_ids[slot_index] = dragged_beast_id
	_update_material_slot_display(slot_index)
	_update_synthesis_button_state()
	
	if selected_beast_id == "":
		print("幻兽已放入副宠槽位 %d，请先选择主宠进行合成" % (slot_index + 1))
	else:
		print("幻兽已放入副宠槽位 %d" % (slot_index + 1))

func _handle_formation_slot_drop(slot_index: int):
	"""处理队伍槽位放置"""
	if slot_index < 0 or slot_index >= formation_slots.size():
		return
	
	# 检查幻兽是否已在队伍中
	if dragged_beast_id in active_formation:
		print("幻兽已在队伍中")
		return
	
	# 检查幻兽是否在副宠槽位中
	if dragged_beast_id in material_beast_ids:
		print("副宠不能加入队伍")
		return
	
	# 尝试加入队伍
	var success = PhantomBeastManager.add_to_formation(dragged_beast_id)
	if success:
		print("幻兽已加入队伍")
		# 保存游戏数据
	if GameSaveManager != null:
		var current_slot = GameSaveManager.current_save_slot
		if current_slot >= 0:
			GameSaveManager.save_game_to_slot(current_slot)
			print("队伍编成变化已保存！")
			# 自动整理背包
			_auto_sort_beasts()
	refresh_beast_grid()
	refresh_formation_display()
	# 刷新当前选中幻兽的显示
	if selected_slot_index >= 0:
		_select_beast(selected_slot_index)
	else:
		print("队伍已满，无法加入更多幻兽")

func _restore_all_slot_styles():
	"""恢复所有格子的样式"""
	# 恢复幻兽格子样式
	for slot in beast_slots:
		var background = slot.get_child(0) as Panel
		if background and slot != highlighted_slot:
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)
			style_box.border_width_left = 1
			style_box.border_width_right = 1
			style_box.border_width_top = 1
			style_box.border_width_bottom = 1
			style_box.border_color = Color(0.5, 0.5, 0.5, 1.0)
			style_box.corner_radius_top_left = 3
			style_box.corner_radius_top_right = 3
			style_box.corner_radius_bottom_left = 3
			style_box.corner_radius_bottom_right = 3
			background.add_theme_stylebox_override("panel", style_box)
	
	# 恢复队伍槽位样式
	for slot in formation_slots:
		var background = slot.get_child(0) as Panel
		if background:
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.2, 0.2, 0.3, 0.9)
			style_box.border_width_left = 2
			style_box.border_width_right = 2
			style_box.border_width_top = 2
			style_box.border_width_bottom = 2
			style_box.border_color = Color(0.6, 0.6, 0.8, 1.0)
			style_box.corner_radius_top_left = 5
			style_box.corner_radius_top_right = 5
			style_box.corner_radius_bottom_left = 5
			style_box.corner_radius_bottom_right = 5
			background.add_theme_stylebox_override("panel", style_box)
	
	# 恢复副宠槽位样式
	for slot in material_slots:
		var background = slot.get_child(0) as Panel
		if background:
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.2, 0.3, 0.2, 0.9)
			style_box.border_width_left = 2
			style_box.border_width_right = 2
			style_box.border_width_top = 2
			style_box.border_width_bottom = 2
			style_box.border_color = Color(0.6, 0.8, 0.6, 1.0)
			style_box.corner_radius_top_left = 5
			style_box.corner_radius_top_right = 5
			style_box.corner_radius_bottom_left = 5
			style_box.corner_radius_bottom_right = 5
			background.add_theme_stylebox_override("panel", style_box)

func _on_material_slot_input(event: InputEvent, slot_index: int):
	"""副宠槽位输入处理"""
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_RIGHT and event.pressed:
			# 右键移除副宠
			if slot_index < material_beast_ids.size() and material_beast_ids[slot_index] != "":
				material_beast_ids[slot_index] = ""
				_update_material_slot_display(slot_index)
				_update_synthesis_button_state()
				print("副宠已从槽位 %d 移除" % (slot_index + 1))
				
				# 自动整理背包
				_auto_sort_beasts()

func _on_formation_changed(_active_beasts: Array[Dictionary]):
	"""队伍变化时的处理"""
	refresh_beast_grid()
	refresh_formation_display()

func _on_sort_button_pressed():
	"""整理按钮点击处理"""
	if PhantomBeastManager == null:
		return
	
	# 获取排序后的幻兽数据
	var sorted_beasts = PhantomBeastManager.sort_phantom_beasts()
	
	# 使用排序后的数据刷新显示
	refresh_beast_grid_with_sorted_data(sorted_beasts)
	
	# 清空当前选择
	_clear_beast_info()
	_clear_highlight()
	formation_button.disabled = true
	sell_button.disabled = true
	revive_button.disabled = true
	revive_button.visible = false
	
	# 保存游戏数据
	if GameSaveManager != null:
		var current_slot = GameSaveManager.current_save_slot
		if current_slot >= 0:
			GameSaveManager.save_game_to_slot(current_slot)
			print("幻兽背包整理完成并已保存！")
	else:
		print("幻兽背包整理完成！")

func _auto_sort_beasts():
	"""自动整理幻兽背包"""
	if PhantomBeastManager == null:
		return
	
	# 获取排序后的幻兽数据
	var sorted_beasts = PhantomBeastManager.sort_phantom_beasts()
	
	# 使用排序后的数据刷新显示
	refresh_beast_grid_with_sorted_data(sorted_beasts)
	
	print("幻兽背包已自动整理！")
